import 'package:bloc_usage/bloc/Bloc.dart';
import 'package:flutter/material.dart';

class BlocProvider<T extends Bloc> extends StatefulWidget {
  final T bloc;
  final Widget child;

  BlocProvider({Key key, @required this.child, @required this.bloc})
      : super(key: key);

  static T of<T extends Bloc>(BuildContext context) {
    Type type = _typeOf<BlocProvider<T>>();
    BlocProvider<T> blocProvider = context.ancestorWidgetOfExactType(type);
    return blocProvider.bloc;
  }

  static _typeOf<T>() => T;

  @override
  State<StatefulWidget> createState() => _BlocProviderState();

  // @override
  // Widget build(BuildContext context) {
  //   return child;
  // }
}

class _BlocProviderState extends State<BlocProvider> {
  @override
  void dispose() {
    widget.bloc.release();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
